import { Button, Table, message as antdMessage } from "antd";
import axios from "axios";
import React, { useEffect, useRef, useState } from "react";

interface ListRawState {
  name: string;
  owner: {
    id: string;
  };
  size: number;
  url: string;
}

const Index: React.FC = () => {
  const [list, setList] = useState<ListRawState[]>([]);
  const inputRef = useRef<HTMLInputElement | null>(null);
  const columns = [
    // {
    //   key: "id",
    //   title: "id",
    //   dataIndex: "owner",
    //   render(owner: { id: string }) {
    //     return <span>{owner.id}</span>;
    //   },
    // },
    {
      key: "name",
      title: "文件名称",
      dataIndex: "name",
    },
    {
      key: "size",
      title: "文件大小",
      dataIndex: "size",
    },
    {
      key: "url",
      title: "文件路径",
      dataIndex: "url",
      render(url: string) {
        return (
          <div>
            <span onClick={() => antdMessage.success("路径为:" + url)}>
              查看路径
            </span>
            <a href={url}>下载文件</a>
          </div>
        );
      },
    },
    {
      key: "image",
      title: "展示图片",
      dataIndex: "url",
      render(url: string) {
        return (
          <div>
            <img
              src={url}
              alt="暂无图片"
              width={50}
              height={50}
              style={{ objectFit: "cover" }}
            />
          </div>
        );
      },
    },
    {
      key: "opration",
      title: "操作",
      render(row: ListRawState) {
        return (
          <div>
            <Button type="primary" danger onClick={() => handleDelete(row)}>
              删除
            </Button>
          </div>
        );
      },
    },
  ];
  // input change 事件  => 文件的内容发生了改变
  const handleChange = () => {
    // 1. 获取input
    const input = inputRef.current as HTMLInputElement;
    // 2. 获取上传的文件列表
    const files = input.files as FileList;
    // 3. 获取上传的单个文件
    const file = files[0];

    if (!file) return;
    if (!file.type.includes("image")) {
      antdMessage.error("上传的文件只可以是图片");
      return;
    }
    // 4. 调用上传文件函数
    upload("/api/upload", file);
  };

  // 上传文件函数
  const upload = async (url: string, file: File) => {
    // 1. 创建formData实例
    const formData = new FormData();
    // 2. 添加 formdata 数据
    formData.append("file", file, file.name);
    // 3. 发送请求
    const resp = await axios.post(url, formData);

    
    const { code, message, error } = resp.data;
    if (code === 200) {
      antdMessage.success(message);
      fetchList();
    } else {
      antdMessage.error(message);
      console.log(error);
    }
  };

  // 删除函数
  const handleDelete = async (row: ListRawState) => {
    const { name } = row;
    const resp = await  axios.delete('/api/upload', { params: { name } })
    console.log(resp.data)
    fetchList();
  };

  // 请求函数
  const fetchList = () => {
    axios.get("/api/upload/list").then((resp) => {
      console.log(resp.data.data.objects);
      setList(resp.data.data.objects);
    });
  };

  useEffect(() => {
    fetchList();
  }, []);
  return (
    <div>
      <input
        type="file"
        ref={inputRef}
        onChange={() => handleChange()}
        style={{ display: "none" }}
      />
      <Button type="primary" onClick={() => inputRef.current?.click()}>
        上传
      </Button>

      <Table
        columns={columns}
        dataSource={list}
        rowKey={(row) => row.owner.id}
        scroll={{
          x: "100%",
        }}
      ></Table>
    </div>
  );
};

export default Index;
